import Vue from 'vue'
import store from '@/store'
import router from '@/router'
import cookie from '@/util/cookie'
import wechat from "@/util/wechat"
import { publicUrl } from '@/config/config'
import { getAccessToken, getTokenByMoblie, getTeacher, getRoleList, refreshToken, getTeacherByLoginUserId } from '@/api/commonApi'
import {getCookiesObj, setCookie, checkArr, unique, getCookie} from '@/util/tool'
import {getSchool} from '@/api/schoolApi'

const user = {
  namespaced: true,
  state: {
    access_token: '',
    testImg: 'static/zanwu.png',
    headImg: '',
    classId: '',
    className: '',
    gradeId: '',
    gradeName: '',
    schoolId: '',
    schoolName: '',
    childList: [],
    classList: [],
    teacherId: '',
    realName: '',
    loginUserId: '',
    parentId: '',
    studentId: '',
    studentImg: '',
    roleCode: '',
    studentName: '',
    isSchoolAdmin: false,
    isNoClass: false,
    cookiesObj: {},
    reloadToken: true,

    isMini: cookie.get('isMini') ? true : false


  },
  getters: {
    cellPhoneNum (state) {
      var s = cookie.get('cellPhoneNum')
      if (!s) {
        return null
      }
      return s
    },
    classId (state) {
        return state.classId
    },
    gradeId (state) {
     return state.gradeId
    },
    schoolId (state) {
      return state.schoolId
    },
    studentId (state) {
      return state.studentId
    },
    studentName (state) {
      return state.studentName
    },
    parentId (state) {
      return state.parentId
    },
    teacherId (state) {
      return state.teacherId
    },
    roleCode (state) {
      return state.roleCode
    },
    loginUserId (state) {
      return state.loginUserId
    },
    realName (state) {
      return state.realName
    },
    loginName (state) {
        return state.LoginName
    },
    img () {
      var s = cookie.get('img')
      if (!s) {
        s = 'http://file.xueerqin.net/PortraitFiles/eeeea2b869e44b3bbd797f4d781aceaf/14ea81d3ada5490cb1b2d128d109bca0.png'
      }
      return s
    }
  },
  mutations: {
      setRoleCode (state, val) {
        state.roleCode = val
        setCookie('roleCode', val, 0)
      }
  },
  actions: {
    getAccessToken ({ state }) {
      return new Promise((resovle, reject) => {
        if (state.access_token) {
          resovle(state.access_token)
        } else {
          getAccessToken().then(res => {

            res = JSON.parse(res)
            state.access_token = res.Data.accessToken
            resovle(state.access_token)
          })
        }

      })
    },
    changePerson ({ state, dispatch }, item) {
      
        if (getCookie('roleCode') == 'Teacher') {
            setCookie('schoolId', item.SchoolId, 0)
            setCookie('classId', item.ClassId, 0)
            setCookie('gradeId', item.GradeId, 0)

            state.schoolId = item.SchoolId
            state.classId = item.ClassId
            state.gradeId = item.GradeId

            localStorage.setItem('itemDataTeacher', JSON.stringify(item))
        } else if (getCookie('roleCode') == 'Parent') {
            setCookie('schoolId', item.SchoolId, 0)
            setCookie('studentId', item.SelfId, 0)
            setCookie('classId', item.ClassId, 0)
            setCookie('gradeId', item.GradeId, 0)
            setCookie('img', item.Img, 0)

            state.schoolId = item.SchoolId
            state.studentId = item.SelfId
            state.classId = item.ClassId
            state.gradeId = item.GradeId

            localStorage.setItem('itemData', JSON.stringify(item))
        }

        location.reload()
    },
     getUserInfo ({ state, dispatch }) {
      return new Promise(async (resolve, reject) => {
      //   if(!getCookie('roleCode')){
      //     return
      //  }
        if (!state.reloadToken) {
          resolve()
          return
        }
        state.reloadToken = false

        var res = await getTokenByMoblie()
        await wechat.start()

        console.log(res)
        if (!res.Data) {
          resolve()
          return
        }
        state.roleCode = getCookie('roleCode')


        if (getCookie('roleCode') == 'Teacher') {

            await dispatch('teacherHandle', res)
            // await dispatch('getTeacher')
            await dispatch('getRoleList')
        } else if (getCookie('roleCode') == 'Parent') {
          console.log(getCookie('roleCode'))
            dispatch('parentHandle', res)
        }
        resolve()

      })
    },
    parentHandle ({ state, dispatch }, res) {
      // 陈勇的逻辑
      setCookie('loginUserId', res.Data.UserId, 0)
      setCookie('parentId', res.Data.SelfId, 0)
      setCookie('realName', encodeURI(res.Data.RealName), 0)

      var children = res.Data.MChildList
      for (var i = children.length - 1; i >=0; i--) {
        if (!children[i].ClassId) {
          children.splice(i,1)
        }
      }

      if (children.length == 0) {
          Vue.$vux.alert.show({
            content: '您还没有绑定孩子，请添加孩子。',
            maskZIndex: 100,
            onHide () {
                router.push('/myNew/children')

            }
          })
          return
      }


      localStorage.setItem('mChildList', JSON.stringify(children))
      state.cookiesObj = getCookiesObj(document.cookie)

      // 路奇的逻辑
      state.child = ''
      let itemData = localStorage.getItem('itemData')
        if(itemData){
          itemData = JSON.parse(itemData)
          for (var ch of children) {

            if (ch.SelfId == itemData.SelfId) {
              state.child = ch
            }
          }
        }
        if (!state.child) {
          state.child = children[0]
        }

        localStorage.setItem('itemData', JSON.stringify(state.child))

        setCookie('schoolId', state.child.SchoolId, 0)
        setCookie('studentId', state.child.SelfId, 0)
        setCookie('classId', state.child.ClassId, 0)
        setCookie('gradeId', state.child.GradeId, 0)
        setCookie('img', state.child.Img, 0)

        state.cookiesObj = getCookiesObj(document.cookie)


        state.headImg = res.Data.Img
        state.loginName = res.Data.LoginName
        state.childList = res.Data.MChildList
        state.parentId = res.Data.SelfId
        state.realName = res.Data.RealName
        state.loginUserId = res.Data.UserId

        state.classId = state.child.ClassId
        state.className = state.child.ClassName
        state.gradeId = state.child.GradeId
        state.gradeName = state.child.GradeName
        state.schoolId = state.child.SchoolId
        state.schoolName = state.child.SchoolName
        state.studentName = state.child.RealName
        state.studentId = state.child.SelfId
        state.studentImg = state.child.Img

        state.isMain = false



      },
      async teacherHandle ({ state, dispatch }, res) {
        // 路奇的逻辑
        state.headImg = res.Data.Img
        state.classList = res.Data.ClassInfoList ? res.Data.ClassInfoList : []
        state.teacherId = res.Data.SelfId
        state.realName = res.Data.RealName
        state.schoolId = res.Data.SchoolId

        var school = await getSchool(res.Data.SchoolId)
        state.schoolName = school.name

        state.loginUserId = res.Data.UserId

        // 陈勇的逻辑
        setCookie('img', res.Data.Img, 0)
        setCookie('loginUserId', res.Data.UserId, 0)
        setCookie('teacherId', res.Data.SelfId, 0)
        setCookie('realName', encodeURI(res.Data.RealName), 0)
        setCookie('schoolId', res.Data.SchoolId, 0)
        setCookie('loginName', res.Data.LoginName, 0)


      

        if(!state.classList || state.classList.length == 0){
            state.isNoClass = true
          
            return
        }

    

        localStorage.setItem('classInfoList', JSON.stringify(state.classList))




        state.class = ''
        let itemDataTeacher = localStorage.getItem('itemDataTeacher')

        if (itemDataTeacher) {
          itemDataTeacher = JSON.parse(itemDataTeacher)
          for (var cl of state.classList) {
            if (cl.ClassId == itemDataTeacher.ClassId) {
              state.class = cl
            }
          }
        }

        if (!state.class) {
          state.class = state.classList[0]
        }


        localStorage.setItem('itemDataTeacher', JSON.stringify(state.class))
        state.classId = state.class.ClassId
        state.gradeId = state.class.GradeId
        setCookie('classId', state.class.ClassId, 0)
        setCookie('gradeId', state.class.GradeId, 0)


        state.cookiesObj = getCookiesObj(document.cookie)

      },

    getTeacher ({ state }) {
      return new Promise((resolve, reject) => {
        getTeacher(getCookie('teacherId')).then(res => {
          res = JSON.parse(res)
          res = JSON.parse(res)
          var list = res.data

          for (var item of list) {
            var isHave = false
            for (var i = 0; i < state.classList.length; i++) {
              if (state.classList[i].ClassId == item.Id) {
                state.classList[i].isMain = true
                state.classList[i].IsMain = true
                state.classList[i].parentName = '班主任'
                isHave = true
              }
            }
            if (!isHave) {
              state.classList.push({
                ClassId: item.Id,
                ClassName: item.Name,
                GradeId: item.GradeId,
                GradeName: item.GradeName,
                SchoolId: item.SchoolId,
                SchoolName: item.SchoolName,
                IsMain: true,
                isMain: true,
                parentName : '班主任'
              })
            }

          }

         
          resolve()
        })
      })
    },

    getRoleList ({ state }) {
      var params = {
        userId: getCookie('loginUserId')
      }
      getRoleList(params).then(
        res => {

         for (var item of res) {
          if (item.code == 'SchoolAdmin') {
              state.isSchoolAdmin = true
          }
         }

        }
      )
    },

    async refreshAccessToken ({state}) {
      var authToken = cookie.get('authToken')
      authToken = decodeURIComponent(authToken)
      var params = {
        refresh_Token: (JSON.parse(authToken)).refresh_token
      }
      let res = await refreshToken(params)
      let domain = '.xueerqin.net'
      cookie.set('authToken', decodeURIComponent(JSON.stringify(res)), 0, domain)
    },

    async getTeacherByLoginUserId ({state}) {
      let loginUserId =  cookie.get('loginUserId')
      let res = await getTeacherByLoginUserId(loginUserId)
      
      state.teacherId = res.id
      state.roleCode = 'Teacher'

      let domain = '.xueerqin.net'
      cookie.set('roleCode', 'Teacher', 0, domain)
    }
  }
}
export default user
